package cn.huapu.power.energy.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 老时间方式的处理
 * @author hunter
 *
 */
public class OldDateDeserializer extends StdScalarDeserializer{
	private final String[] DATE_FORMAT_STRS = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd","HH:mm:ss"};	
	public OldDateDeserializer(Class<?> vc) {
		super(vc);
	}

	@Override
	public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		JsonToken t = p.getCurrentToken();
        if (t == JsonToken.VALUE_STRING) {
            String str = p.getText().trim();
            int len = str.length();
            if (len == 0) {
                return getEmptyValue(ctxt);
            }
            try {
            	SimpleDateFormat parser = new SimpleDateFormat();
            	int i = 0;
            	if(len <10) {
            		i = 2;
            	}
            	if(len == 10) {
            		i = 1;
            	}
            	parser.applyPattern(DATE_FORMAT_STRS[i]);
                return parser.parseObject(str);
            } catch (ParseException e) {
                return null;
            }
        }
        return super._parseDate(p,ctxt);
	}

}
